<?php
namespace Admin\Controller;
use Common\Controller\RequestController;

class GPSController extends AdminController
{
	public $_suppliers = ['赛格','杨利伟','倪根鸣'];//供应商：1赛格 2杨利伟 3倪根鸣

    protected function _initialize()
    {
		parent::_initialize ();
	}

	protected function getAccessTokenByAcountWithPassword()
	{
		// http://113.105.94.142:809/api/car/getbaseinfo?imei=&key=
		$carOnline = 'http://api.gpsoo.net/1/auth/access_token';
		// 参数名	参数类型	是否必需	默认值	描述
		// account	string	是	无	经销商的账号
		// time	number	是	无	UNIX时间戳，10位，精确到秒
		// signature	string	是	无	加密的签名，算法为:md5(md5(经销商账号的密码) + time)，md5值使用32位小写字符串

		$p_data = ['account' => '杭州融悦','time' => time()];

		$strSignature = md5(md5('95398b').time());

		$p_data['signature'] = $strSignature;

		// $carOnline .= '&signature='.$strSignature;
		// http://113.105.94.142:809/api/car/getlastinfo?imei=&key=
		$ret = RequestController::loadJsonByUrl($carOnline,'post',$p_data);
		session('access_token',$ret['access_token']);

		// if ($ret['ret'])
		// {
		// 	return $ret['msg'];
		// }

		return $ret;//['access_token'];
	}

	public function equipmentsAudit()
	{
		$where = 'g.status = 4';
		// if (I('get.aid', -1, 'intval') <> -1)
		// {
		// 	if(I('get.aid', -1, 'intval')==0){
		// 		$where .=' and  aid =0';
		// 	}else{
		// 		$where .=' and aid='.I('get.aid', 0, 'intval');
		// 	}
		// }
		// $where .= I('get.user_name') != '' ? ' and user_name like "%'.I('get.user_name').'%"' : '';
		// $where .= I('get.telephone') != '' ? ' and telephone = '.I('get.telephone') : '';
		// $where .= I('get.create_time_beg') != '' ? ' and create_time >= '.strtotime(I('get.create_time_beg')) : '';
		// $where .= I('get.create_time_end') != '' ? ' and create_time < '.strtotime(I('get.create_time_end')) : '';
		// $where .= I('get.status') !=''? ' and status='.I('get.status') : '';

		$nSumtStock = M('gps g')->where($where)->sum('g.total_stock');

		$list = $this->getList('g.*,a.name','gps g',$where,'g.id desc',true,' join app_admins a on a.id = g.admin_id');
		$this->assign('list', $list);
		$this->assign('sumStock', $nSumtStock);
		$this->display();
	}

	/**
	 * [GPS采购设备申请，状态置为申请待审核4]
	 * @return [type] [description]
	 * @author [NYJ]
	 */
	public function applyEquipment()
	{
		if(IS_POST)
		{
			$nTotalNum    = I('post.total_stock',0,'intval');
			$strNote      = I('post.note');

			$_dataAdd = ['status' => 4 ,'total_stock' => $nTotalNum,'note' => $strNote,
						'create_time' => time(),'update_time' => time(),'admin_id' => session('adminInfo.id')
						];

			$ret = $this->updateData($_dataAdd,'gps');

			if ($ret) {
				$this->redirect('GPS/index');
			}else{
				$this->error('申请添加失败，请联系管理员',U('GPS/apply'),0);
			}

		}
		$this->display();
	}
	/**
	 * [采购申请]
	 * @author NYJ
	 */
	public function apply()
	{
		if(IS_POST)
		{
			$strSuppliers = I('post.suppliers');
			$nTotalNum    = I('post.total_stock',0,'intval');
			$strNote      = I('post.note');

			$_dataAdd = ['status' => 2 ,'suppliers' => $strSuppliers,'total_stock' => $nTotalNum,'note' => $strNote,
						'create_time' => time(),'update_time' => time(),'admin_id' => session('adminInfo.id')
						];

			$ret = $this->updateData($_dataAdd,'gps');

			if ($ret) {
				$this->redirect('GPS/index');
			}else{
				$this->error('申请添加失败，请联系管理员',U('GPS/apply'),0);
			}

		}
		$this->assign('suppliers',$this->_suppliers);
		$this->display();
	}

	public function completeAllot()
	{
		if (IS_POST)
		{
			$ret = $this->updateData(['status' => 10,'update_time' => time()],'advance',2,['id' => $_POST['advanceId']]);
		}
		echo json_encode(['status' => $ret ]);exit();
	}
	/**
	 * [分配设备给用户]
	 * @param string $value [description]
	 * @author NYJ
	 */
	public function addEquip()
	{
		if (IS_POST)
		{
			$nUserId = $_POST['user_id'];
			$nId     = $_POST['device_number'];

			$retUp = $this->updateData(['user_id' => $nUserId,'update_time' => time()],'gpsequipment',2,['id' => $nId]);

			if ($retUp)
			{
				$this->redirect('GPS/allotEquipList');
			}else{
				$this->error('设备分配失败，请联系管理员',U('GPS/allotEquipList'),0);
			}

		}

		if (session('adminInfo.gpid'))
		{
			$nGroup_id = session('adminInfo.gpid');
		}else{
			$nGroup_id = session('adminInfo.gid');
		}

		$arrWhere = ['user_id' => 0 ,'group_id' => $nGroup_id];

		$gpsEquipments = $this->getList('id,device_number','gpsequipment',$arrWhere,'id desc');

		$this->assign('gpsEquipments',$gpsEquipments);
		$this->display();
	}

	/**
	 * [根据gps编号，调用接口，获取经纬度 展示于百度地图]
	 * @return [type] [description]
	 * @author NYJ
	 */
	public function showPosition()
	{
		$nEquipmentId = I('get.equipment_id',0,'intval');

		$_tmp = $this->getInfo('*','gpsequipment',['id' => $nEquipmentId]);

		switch ($_tmp['suppliers'])
		{
			case '杨利伟':
				$_destUrl = 'http://113.105.94.142:97/api/car/getlastinfo';

				$p_data    = ['key' => 'FF6F8BEB-7B1A-40FD-A256-6092ACB801AA','imei' => $_tmp['device_number']];
				$_pInfo = array_change_key_case(RequestController::loadJsonByUrl($_destUrl,'post',$p_data));
				break;

			case '倪根鸣':
				$ret = $this->getAccessTokenByAcountWithPassword();
				if ($ret['ret'])
				{
					return $ret['msg'];
				}

				$strToken  = $ret['access_token'];

				$_destUrl  = 'http://api.gpsoo.net/1/devices/tracking';

				$p_data    = ['access_token' => $strToken,'imeis' => $_tmp['device_number']];

				$_tracking = RequestController::loadJsonByUrl($_destUrl,'post',$p_data);

				if ($_tracking['ret'])
				{
					return $_tracking['msg'];
				}

				$_pInfo = array_change_key_case($_tracking['data'][0]);

				$_pInfo['blat']    = $_pInfo['lat'];
				$_pInfo['blng']    = $_pInfo['lng'];
				$_pInfo['comtime'] = date('Y-m-d h:i:s',$_pInfo['gps_time']);

				// 逆地理查询具体位置
				$_url                     = 'http://api.gpsoo.net/1/tool/address';
				$p_url_data               = ['access_token' => $strToken,'lng' => $_pInfo['lng'],'lat' => $_pInfo['lat']];
				$_detailPosition          = RequestController::loadJsonByUrl($_url,'post',$p_url_data);
				$_pInfo['addr']['Detail'] = $_detailPosition['address'];
				break;

			case '赛格':
				$_destUrl   = '120.76.69.92:7515/VehicleData/GetVehicleBaseData.json';//type 可选值：1：JSON，2：XML
				$p_url_data = ['key' => '0301fe74-4cee-4aec-82da-852b2f3b6b06'];
				$result     = RequestController::loadJsonByUrl($_destUrl,'post',$p_url_data);

				if ($result['flag'])
				{
					$retList = $result['obj'];
				}

				foreach ($retList as $value)
				{
					if ($value['terminalNo'] == $_tmp['device_number'])
					{
						$id = $value['id'];
						break;
					}
				}

				$_url             = '120.76.69.92:7515/VehicleData/GetPosData.json';
				$p_url_data['id'] = $id;
				$ret              = RequestController::loadJsonByUrl($_url,'post',$p_url_data);

				if ($ret['flag'])
				{
					$_pInfo = $ret['obj'][$id];
				}

				$_pInfo['blat']    = $_pInfo['lat'];
				$_pInfo['blng']    = $_pInfo['lon'];
				$_pInfo['imei']    = $_tmp['device_number'];
				$_pInfo['comtime'] = date('Y-m-d h:i:s',$_pInfo['gpsTime']);

				// 逆地理查询具体位置
				$_pInfo['addr']['Detail'] = '系统无法提供具体位置';
				break;

			default:
				# code...
				break;
		}

		$this->assign('pInfo',$_pInfo);
		$this->display();
	}

	/**
	 * [GPS设备查看列表]
	 * @return [type] [显示view]
	 * @author NYJ
	 */
	public function equipList()
	{
		if (session('adminInfo.gpid'))
		{
			$nGroup_id = session('adminInfo.gpid');
		}else{
			$nGroup_id = session('adminInfo.gid');
		}

		$_tmpList = $this->getList('*','gpsequipment','user_id != 0 and group_id = '.$nGroup_id,'id desc',true);

		$this->assign('equipmentList',$_tmpList);
		$this->display();
	}

	/**
	 * [分配GPS设备列表]
	 * @return [type] [description]
	 * @author NYJ
	 */
	public function allotEquipList()
	{
		$_advanceList = $this->getList('*','advance','status >= 3 and status < 10','id desc',true);

		$this->assign('advanceList',$_advanceList);
		$this->display();
	}

	/**
	 * [我的采购]
	 * @return [mixed] [根据当前管理者身份显示本部门采购申请]
	 * @author [NYJ]
	 */
	public function myPurchasing()
	{
		$where = ['admin_id' => session('adminInfo.id')];


		$nSumtStock = M('gps g')->where($where)->sum('g.total_stock');

		$list = $this->getList('g.*,a.name','gps g',$where,'g.id desc',true,' join app_admins a on a.id = g.admin_id');
		$this->assign('list', $list);
		$this->assign('sumStock', $nSumtStock);
		$this->display();
	}

	public function index()
	{
		$where = 'g.status = 0';
		// if (I('get.aid', -1, 'intval') <> -1)
		// {
		// 	if(I('get.aid', -1, 'intval')==0){
		// 		$where .=' and  aid =0';
		// 	}else{
		// 		$where .=' and aid='.I('get.aid', 0, 'intval');
		// 	}
		// }
		// $where .= I('get.user_name') != '' ? ' and user_name like "%'.I('get.user_name').'%"' : '';
		// $where .= I('get.telephone') != '' ? ' and telephone = '.I('get.telephone') : '';
		// $where .= I('get.create_time_beg') != '' ? ' and create_time >= '.strtotime(I('get.create_time_beg')) : '';
		// $where .= I('get.create_time_end') != '' ? ' and create_time < '.strtotime(I('get.create_time_end')) : '';
		// $where .= I('get.status') !=''? ' and status='.I('get.status') : '';

		$nSumtStock = M('gps g')->where($where)->sum('g.total_stock');

		$list = $this->getList('g.*,a.name','gps g',' 1 = 1','g.id desc',true,' join app_admins a on a.id = g.admin_id');
		$this->assign('list', $list);
		$this->assign('sumStock', $nSumtStock);
		$this->display();
	}

	/**
	 * [GPS待审]
	 * @return [mix] [展示待审以供财务助理审核]
	 * @author NYJ
	 */
	public function audit()
	{
		$where = 'g.status = 2';
		// if (I('get.aid', -1, 'intval') <> -1)
		// {
		// 	if(I('get.aid', -1, 'intval')==0){
		// 		$where .=' and  aid =0';
		// 	}else{
		// 		$where .=' and aid='.I('get.aid', 0, 'intval');
		// 	}
		// }
		// $where .= I('get.user_name') != '' ? ' and user_name like "%'.I('get.user_name').'%"' : '';
		// $where .= I('get.telephone') != '' ? ' and telephone = '.I('get.telephone') : '';
		// $where .= I('get.create_time_beg') != '' ? ' and create_time >= '.strtotime(I('get.create_time_beg')) : '';
		// $where .= I('get.create_time_end') != '' ? ' and create_time < '.strtotime(I('get.create_time_end')) : '';
		// $where .= I('get.status') !=''? ' and status='.I('get.status') : '';

		$nSumtStock = M('gps g')->where($where)->sum('g.total_stock');

		$list = $this->getList('g.*,a.name','gps g',$where,'g.id desc',true,' join app_admins a on a.id = g.admin_id');
		$this->assign('list', $list);
		$this->assign('sumStock', $nSumtStock);
		$this->display();
	}

	/**
	 * [审核GPS采购申请]
	 * @return [int] [审核结果]
	 * @author NYJ
	 */
	public function checkYes()
	{
		if (IS_POST)
		{
			$nGPSID = $_POST['gpsId'];

			echo $this->updateData(['status' => 0,'update_time' => time()],'gps',2,['id' => $nGPSID]);
		}

	}

	/**
	 * [审核GPS设备申请]
	 * @return [int] [审核结果]
	 * @author NYJ
	 */
	public function checkEquipYes()
	{
		if (IS_POST)
		{
			$nGPSID = $_POST['gpsId'];

			echo $this->updateData(['status' => 5,'update_time' => time()],'gps',2,['id' => $nGPSID]);
		}

	}

	/**
	 * [设备审核兼设备详情上传]
	 * @return [json] [操作提示]
	 */
	public function importGps()
	{
		$nGPSID           = $_POST['gps_id'];
		$_tmpFilename     = $_FILES['tmp_name'];
		$upload           = new \Think\Upload();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->exts     = array('xlsx', 'xls', 'csv');// 设置附件上传类型
		$upload->rootPath = './Uploads/'; // 设置附件上传根目录
		$upload->savePath = ''; // 设置附件上传（子）目录
		// 上传文件
		$info   =   $upload->upload();

		// 上传失败返回错误提示
		if (!$info)
		{
			$this->updateData(['status' => 4,'update_time' => time()],'gps',2,['id' => $nGPSID]);
			echo json_encode(['status' => 0,'errorMsg' => $upload->getError()]);
			exit();
		}

		$info['status'] = 1;

		// if(!$info)
		// {
			// 上传错误提示错误信息
            // return $this->ajaxReturn(array('status' => -1, 'info' => $upload->getError()));
		    // return $this->error($upload->getError());
		// }else
		$_tmpFilename = './Uploads/'.$info['gps_excel']['savepath'].$info['gps_excel']['savename'];

		include VENDOR_PATH . 'PHPExcel/PHPExcel.php';

		$type = strtolower($info['gps_excel']['ext']);
		if($type == 'xlsx' || $type == 'xls' )
		{
	        $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文档
	    }
	    else if( $type=='csv' )
	    {
	        $objReader = \PHPExcel_IOFactory::createReader('CSV'); // 读取 excel 文档
	    }
	    else
	    {
	        echo json_encode(['status' => 0,'errorMsg' => 'Not supported file types!']);
			exit();
	    }

		$objReader->setReadDataOnly(true);
		$objPHPExcel        = $objReader->load($_tmpFilename);
		$objWorksheet       = $objPHPExcel->getActiveSheet();
		$highestRow         = $objWorksheet->getHighestRow();
		$highestColumn      = $objWorksheet->getHighestColumn();
		$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
		$temp  = array();

		if (session('adminInfo.gpid'))
		{
			$nGroup_id = session('adminInfo.gpid');
		}else{
			$nGroup_id = session('adminInfo.gid');
		}

		for ($row = 1; $row <= $highestRow; $row++)//行数是以第1行开始
		{
		    for ($column = 0; $column < $highestColumnIndex; $column++) //列数是以A列开始
		    {
				// $temp[$row][] = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();
				// $temp[]       = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();
				$strDeviceNumber = $objWorksheet->getCellByColumnAndRow($column,$row)->getValue();
				if($strDeviceNumber != '设备号')
				{
					$_tmpData = ['suppliers' => $_POST['_suppliers'],'device_number' => $strDeviceNumber,'gps_id' => $nGPSID,
			       				'group_id' => $nGroup_id,'update_time' => time(),'create_time' => time()];
			        $this->updateData($_tmpData,'gpsequipment');
				}
		    }
		}

		$ret = $this->updateData(['suppliers' => $_POST['_suppliers'],'update_time' => time()],'gps',2,['id' => $nGPSID]);

		echo json_encode(['status' => $ret ]);exit();
	}
}